package com.twang.stock.service;

import com.twang.stock.entity.User;
import com.twang.stock.mapper.UserMapper;
import com.twang.stock.redis.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class UserService {
    public static String TOKEN="token";
    @Resource
    private UserMapper userMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private HttpSession httpSession;

    public User getUser(User user){
        Example example=new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotEmpty(user.getUserName())){
            criteria.andEqualTo("userName",user.getUserName());
        }
        if(StringUtils.isNotEmpty(user.getPassword())){
            criteria.andEqualTo("password",user.getPassword());
        }
        if(StringUtils.isNotEmpty(user.getToken())){
            criteria.andEqualTo(TOKEN,user.getToken());
        }
       List<User> users= userMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(users)){
           return users.get(0);
        }
        return null;
    }

    /**
     * 根据TOKEN 获取用户信息
     * @return
     */
    public User getUserByToken() {
        Object token = httpSession.getAttribute(TOKEN);
        if (null == token) {
            return null;
        }
        Object object = redisUtil.get(token.toString());
        if (null == object) {
            return null;
        } else {
            String token1 = object.toString();
            User userPram = new User();
            userPram.setToken(token1);
            User user = getUser(userPram);
            return user;
        }

    }

    public void addUser(User user){
        userMapper.insert(user);
    }
}
